import Box2 from "./Box2";

/**
 * 掉落盒子脚本，实现盒子碰撞及回收流程
 */
export default class Box1 extends Laya.Script {
    /**刚体对象引用 */
    _rig: Laya.RigidBody;

    /** @prop {name:nextLevelBox,tips:"掉落容器预制体对象1",type:Prefab}*/
    nextLevelBox: Laya.Prefab;

    isTrigger: boolean;

    /* 构造函数 */
    constructor() { 
        super(); 
        this.isTrigger = false;
    }

    onEnable(): void {
        /**获得组件引用，避免每次获取组件带来不必要的查询开销 */
        this._rig = this.owner.getComponent(Laya.RigidBody);
    }

    onUpdate(): void {
       
    }

    onTriggerEnter(other: any, self: any, contact: any): void {
        var owner: Laya.Sprite = this.owner as Laya.Sprite;

        switch(other.label){
            case("box2"):{
                if (owner.parent) {
                    /* start--- 播放碰撞动画 ---start */
                    let effect: Laya.Animation = Laya.Pool.getItemByCreateFun("effect", this.createEffect, this);
                    effect.pos(owner.x, owner.y);
                    owner.parent.addChild(effect);
                    effect.play(0, true);
                    /* end--- 播放碰撞动画 ---end */

                    /* 移除碰撞当前盒子 */
                    owner.removeSelf();
                    /* 播放碰撞音效 */
                    Laya.SoundManager.playSound("sound/destroy.wav");
                }
            }

        }

        // if (other.label === "box1") {
        //     Laya.SoundManager.playSound("sound/hit.wav");
        //     if (owner.parent) {
        //         /* start--- 播放碰撞动画 ---start */
        //         let effect: Laya.Animation = Laya.Pool.getItemByCreateFun("effect", this.createEffect, this);
        //         effect.pos(owner.x, owner.y);
        //         owner.parent.addChild(effect);
        //         effect.play(0, true);
        //         /* end--- 播放碰撞动画 ---end */

        //         /* 移除碰撞当前盒子 */
        //         owner.removeSelf();
        //         /* 播放碰撞音效 */
        //         Laya.SoundManager.playSound("sound/destroy.wav");
        //     }
        //     this.isTrigger = true;
        // }else {
        //     this.isTrigger = false;
        // }
    }

    /**使用对象池创建爆炸动画 */
    createEffect(): Laya.Animation {
        let ani: Laya.Animation = new Laya.Animation();
        ani.loadAnimation("test/TestAni.ani");
        ani.on(Laya.Event.COMPLETE, null, recover);
        function recover(): void {
            ani.removeSelf();
            Laya.Pool.recover("effect", ani);
        }
        return ani;
    }

    getTriggerStatus(): boolean {
        console.log("是否碰撞"+this.isTrigger);
        return this.isTrigger;
    }

    onDisable(): void {
        //盒子被移除时，回收盒子到对象池，方便下次复用，减少对象创建开销。
        Laya.Pool.recover("box1", this.owner);
    }
}